//
//  UIView+Extension.swift
//  zhengwutong
//
//  Created by Bernie on 16/8/22.
//  Copyright © 2016年 wangshuguan. All rights reserved.
//

import UIKit
import WebKit
class AllCornersView:UIView{
    override class var layerClass: AnyClass {
        get{
            return CAShapeLayer.self
        }
    }
    func setCornor(color:UIColor = .white,corners:UIRectCorner = .allCorners) {
        var _color = color
        if self.backgroundColor != nil{
            _color = self.backgroundColor!
            self.backgroundColor = nil
        }
        let layer = self.layer as! CAShapeLayer
        let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width - 20, height: self.frame.size.height)
        
        layer.path = UIBezierPath(roundedRect: frame, byRoundingCorners: corners, cornerRadii: CGSize(width: 6, height: 6)).cgPath
        layer.fillColor = _color.cgColor
    }
}
extension UIScreen {
    var width:CGFloat!{
        get{
            return UIScreen.main.bounds.width
        }
    }
    var height:CGFloat!{
        get{
            return UIScreen.main.bounds.height
        }
    }
    static func startAnimation() {
        UIScreen.stopAnimation()
        let aniview = UIActivityIndicatorView(style: .large)
        aniview.tag = 1002
        let aa = UIView(frame: CGRect(x: -10, y: -10, width: aniview.et_width+20, height: aniview.et_height+20))
        aa.backgroundColor = UIColor.black
        aa.layer.cornerRadius = 8
        aa.layer.masksToBounds = true
        aniview.addSubview(aa)
        aniview.sendSubviewToBack(aa)
        aniview.backgroundColor = UIColor.black
        aniview.startAnimating()
        if #available(iOS 13.0, *) {
            aniview.center = UIApplication.shared.windows.first?.center ?? .zero
            UIApplication.shared.windows.first?.addSubview(aniview)
        }else{
            aniview.center = UIApplication.shared.keyWindow?.center ?? .zero
            UIApplication.shared.keyWindow?.addSubview(aniview)
        }
    }
    static func stopAnimation() {
        var window:UIWindow?
        if #available(iOS 13.0, *) {
            window = UIApplication.shared.windows.first
        }else{
            window = UIApplication.shared.keyWindow
        }
        for temp in window?.subviews ?? [] {
            if temp is UIActivityIndicatorView,temp.tag == 1002 {
                temp.removeFromSuperview()
                break
            }
        }
    }
    static func startFullAnimation(text:String,isProcess:Bool = false) {
        NSLog("\(text)")
        if !isProcess{
            UIScreen.stopFullAnimation()
        }
        var control:UIControl?
        var window:UIWindow?
        if #available(iOS 13.0, *) {
            window = UIApplication.shared.windows.first
        }else{
            window = UIApplication.shared.keyWindow
        }
        for temp in window?.subviews ?? [] {
            if temp is UIControl,temp.tag == 1001 {
                control = temp as? UIControl
                break
            }
        }
        if control == nil{
            control = UIControl(frame: CGRect(x: -10, y: -10, width: UIScreen.main.width+20, height: UIScreen.main.height+20))
            control?.tag = 1001
            control?.backgroundColor = UIColor(white: 0, alpha: 0.7)
            let aniview = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.large)
            let aa = UIView(frame: CGRect(x: -10, y: -10, width: aniview.et_width+20, height: aniview.et_height+20))
            aa.backgroundColor = UIColor.black
            aa.layer.cornerRadius = 8
            aa.layer.masksToBounds = true
            aniview.addSubview(aa)
            aniview.sendSubviewToBack(aa)
            aniview.backgroundColor = UIColor.black
            aniview.center = control?.center ?? .zero
            aniview.startAnimating()
            control?.addSubview(aniview)
            let l = UILabel(frame: CGRect(x: 0, y: UIScreen.main.height/2.0 + 50, width: UIScreen.main.width, height: 40))
            l.textColor = .white
            l.textAlignment = .center
            control?.addSubview(l)
            var window:UIWindow?
            if #available(iOS 13.0, *) {
                window = UIApplication.shared.windows.first
            }else{
                window = UIApplication.shared.keyWindow
            }
            window?.addSubview(control!)
        }
        for temp in (control?.subviews)! {
            if temp is UILabel {
                let l = temp as? UILabel
                l?.text = text
                break
            }
        }
    }
    static func stopFullAnimation() {
        var window:UIWindow?
        if #available(iOS 13.0, *) {
            window = UIApplication.shared.windows.first
        }else{
            window = UIApplication.shared.keyWindow
        }
        for temp in window?.subviews ?? [] {
            if temp is UIControl,temp.tag == 1001 {
                temp.removeFromSuperview()
                break
            }
        }
    }
}
extension UIView {
    var et_top:CGFloat{
        set{
            var temp = self.frame;
            temp.origin.y = newValue;
            self.frame = temp;
        }
        get{
            return self.frame.origin.y;
        }
    }
    var et_left:CGFloat{
        set{
            var temp = self.frame;
            temp.origin.x = newValue;
            self.frame = temp;
        }
        get{
            return self.frame.origin.x;
        }
    }
    var et_right:CGFloat{
        set{
            var temp = self.frame;
            temp.origin.x = newValue - temp.size.width;
            self.frame = temp;
        }
        get{
            return self.frame.origin.x + self.frame.size.width;
        }
    }
    var et_bottom:CGFloat{
        set{
            var temp = self.frame;
            temp.origin.y = newValue - temp.size.height;
            self.frame = temp;
        }
        get{
            return self.frame.origin.y + self.frame.size.height;
        }
    }
    var et_width:CGFloat{
        set{
            var temp = self.frame;
            temp.size.width = newValue;
            self.frame = temp;
        }
        get{
            return self.frame.size.width;
        }
    }
    var et_height:CGFloat{
        set{
            var temp = self.frame;
            temp.size.height = newValue;
            self.frame = temp;
        }
        get{
            return self.frame.size.height;
        }
    }
    public func addSubviews(_ views:UIView...){
        for temp in views {
            self.addSubview(temp);
        }
    }
    public func removeAllSubviews(){
        for temp in self.subviews {
            temp.removeFromSuperview();
        }
    }
    var className:String{
        get{
            return NSStringFromClass(self.classForCoder).components(separatedBy: ".").last!
        }
    }
    class var className:String{
        get{
            return NSStringFromClass(self).components(separatedBy: ".").last!
        }
    }
}
extension CALayer{
    func roundWithRadius(_ radius:CGFloat) -> Void {
        self.cornerRadius = radius
        masksToBounds = true
    }
    func borderWithWidth(_ width:CGFloat,color:UIColor) -> Void {
        borderWidth = width
        borderColor = color.cgColor
    }
    func dottedBorderWithWidth(_ width:CGFloat,color:UIColor,size:CGSize) -> Void {
        for x in self.sublayers ?? [] {
            if x.accessibilityLabel == "dotted" {
                x.removeFromSuperlayer()
            }
        }
        let border = CAShapeLayer()
        border.accessibilityLabel = "dotted"
        border.strokeColor = color.cgColor
        border.cornerRadius = 4.0
        border.fillColor = nil
        let _bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        
        border.path = UIBezierPath(rect: _bounds).cgPath
        border.frame = _bounds
        border.lineWidth = width
        border.lineDashPattern = [NSNumber(value: 1), NSNumber(value: 2)]
        self.addSublayer(border)
    }
    func shadowWithColor(_ color:UIColor = .gray,size:CGSize = CGSize(width: 3, height: 3),radius:CGFloat = 5,opacity:Float = 0.4) {
        self.shadowOffset = size
        self.shadowColor = color.cgColor
        self.shadowRadius = radius
        self.shadowOpacity = opacity
    }
}
private var key:Void?
extension UIView {
    class UIViewTapWrapper: NSObject {
        var target:AnyObject
        var action:(()->())?
        init(target:AnyObject,action:(() -> ())?) {
            self.target = target
            self.action = action
        }
        @objc func doAction(){
            if self.action != nil {
                self.action!()
            }
        }
    }
    var tapAction: (()->())?{
        get{
            let wrapper = objc_getAssociatedObject(self, &key) as? UIViewTapWrapper
            return wrapper?.action
        }
        set{
            let wrapper = UIViewTapWrapper(target: self,action:newValue)
            objc_setAssociatedObject(self, &key, wrapper, .OBJC_ASSOCIATION_RETAIN)
            switch self {
            case is UIControl:
                (self as? UIControl)?.addTarget(wrapper, action: #selector(UIViewTapWrapper.doAction), for: .touchUpInside)
            default:
                let tap = UITapGestureRecognizer(target: wrapper, action: #selector(UIViewTapWrapper.doAction))
                self.addGestureRecognizer(tap)
                self.isUserInteractionEnabled = true
            }
        }
    }
    class func xib(_ xibName:String="")->UIView? {
        return Bundle.main.loadNibNamed(xibName.isEmpty ? self.className : xibName, owner: nil, options: nil)?.first as? UIView
    }
    func capture() -> UIImage {
        return self.layer.capture()
    }
    func mask(_ rect:CGRect) {
        let maskLayer = CAShapeLayer()
        maskLayer.fillRule = .evenOdd
        self.layer.mask = maskLayer
        let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))
        let inPath = UIBezierPath(rect: rect)
        path.append(inPath)
        let realPath = path.cgPath
        maskLayer.path = realPath
    }
}
extension CALayer{
    func capture() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 1)
        self.render(in: UIGraphicsGetCurrentContext()!)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img ?? UIImage()
    }
}
extension UIScrollView:UIScrollViewDelegate{
    class UIScrollWrapper: NSObject {
        var scrollAction:((CGFloat)->())?
        init(scrollAction:((CGFloat) -> ())?) {
            self.scrollAction = scrollAction
        }
    }
    var scrollAction: ((CGFloat)->())?{
        get{
            let wrapper = objc_getAssociatedObject(self, &key) as? UIScrollWrapper
            return wrapper?.scrollAction
        }
        set{
            let wrapper = UIScrollWrapper(scrollAction: newValue)
            objc_setAssociatedObject(self, &key, wrapper, .OBJC_ASSOCIATION_RETAIN)
            self.delegate = self
        }
    }
    public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if let sAction = scrollAction {
            var offSetWidth = scrollView.contentOffset.x;
            offSetWidth = offSetWidth +  ((self.frame.size.width + 20) * 0.5)
            let currentIndex = offSetWidth / (self.frame.size.width + 20);
            sAction(currentIndex)
        }
        
    }
}
extension UISearchBar{
    var textFieldBackgroundColor:UIColor?{
        get{
            return textfield()?.backgroundColor
        }
        set{
            textfield()?.backgroundColor = newValue
        }
    }
    private func textfield() -> UITextField? {
        for x in self.subviews{
            if let y = x as? UITextField{
                return y
            }
            for x1 in x.subviews{
                if let y = x1 as? UITextField{
                    return y
                }
                for x2 in x1.subviews{
                    if let y = x2 as? UITextField{
                        return y
                    }
                    for x3 in x2.subviews{
                        if let y = x3 as? UITextField{
                            return y
                        }
                        for x4 in x3.subviews{
                            if let y = x4 as? UITextField{
                                return y
                            }
                            for x5 in x4.subviews{
                                if let y = x5 as? UITextField{
                                    return y
                                }
                            }
                        }
                    }
                }
            }
        }
        return nil
    }
    
    private func bookmarkIcon() -> UIButton? {
        
        guard showsBookmarkButton else {
            return nil
        }
        for x in textfield()?.subviews ?? []{
            if let t = x as? UIButton{
                return t
            }else{
                for x1 in x.subviews{
                    if let t = x1 as? UIButton{
                        return t
                    }
                }
            }
        }
        return nil
    }
    var textFieldTinyColor:UIColor?{
        get{
            return textfield()?.tintColor
        }
        set{
            textfield()?.tintColor = newValue
            textfield()?.textColor = newValue
        }
    }
    func setTextFieldPlaceHolder(attr:NSAttributedString){
        textfield()?.attributedPlaceholder = attr
    }
    func setBookMarkIcon(image:UIImage) {
        showsBookmarkButton = true
        DispatchQueue.main.after(0.1) {[weak self] in
            if let SSelf = self{
                SSelf.bookmarkIcon()?.setImage(image, for: .normal)
                SSelf.bookmarkIcon()?.setImage(image, for: .highlighted)
                SSelf.bookmarkIcon()?.setImage(image, for: .selected)
                SSelf.bookmarkIcon()?.setImage(image, for: .disabled)
            }
        }
    }
}
extension UIImageView{
    func animate(_ named:String){
        guard let path = Bundle.main.path(forResource: named, ofType: nil),
            let data = NSData(contentsOfFile: path),
            let imageSource = CGImageSourceCreateWithData(data, nil) else { return }
        
        var images = [UIImage]()
        var totalDuration : TimeInterval = 0
        for i in 0..<CGImageSourceGetCount(imageSource) {
            guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, i, nil) else { continue }
            let image = UIImage(cgImage: cgImage)
            i == 0 ? self.image = image : ()
            images.append(image)
            
            guard let properties:NSDictionary = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil),
                let gifDict = properties[kCGImagePropertyGIFDictionary] as? NSDictionary,
                let frameDuration = gifDict[kCGImagePropertyGIFDelayTime] as? NSNumber else { continue }
            totalDuration += frameDuration.doubleValue
        }
        
        self.animationImages = images
        self.animationDuration = totalDuration
        self.animationRepeatCount = 0
        
        self.startAnimating()
    }
}
class MYNavigationController: UINavigationController {
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        if self.viewControllers.count > 0{
            viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "contactBack"), style: .plain, target: self, action: #selector(popVC))
            viewController.navigationItem.leftBarButtonItem?.tintColor = UIColor(named: "TextDark1") ?? .black
        }
        if let lst = self.viewControllers.last{
            viewController.runningPath = (lst.runningPath ?? lst.simpleIdentifier) + "-" + viewController.simpleIdentifier
        }
        viewController.runningPath = (self.viewControllers.last?.runningPath ?? "") + "-" + NSStringFromClass(viewController.classForCoder)
        super.pushViewController(viewController, animated: animated)
    }
}
class MYNavigationController2: UINavigationController {
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        if self.viewControllers.count > 0{
            viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "contactBack"), style: .plain, target: self, action: #selector(popVC))
        }
        if let lst = self.viewControllers.last{
            viewController.runningPath = (lst.runningPath ?? lst.simpleIdentifier) + "-" + viewController.simpleIdentifier
        }
        viewController.runningPath = (self.viewControllers.last?.runningPath ?? "") + "-" + NSStringFromClass(viewController.classForCoder)
        super.pushViewController(viewController, animated: animated)
    }
}
extension WKWebView{
    var contentSize:CGSize{
        get{
            return self.scrollView.contentSize
        }
    }
}
